package top.kikt.book.core.base

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import top.kikt.book.core.entity.ChapterMetaEntity

interface IBookHandler : BookHandler, BookMetaHandler, BookChapterHandler, ILogger {

    val host: String

    val hosts: List<String>
        get() = listOf(host)

    /// 猜测是否是当前的类型
    fun guestType(url: String): Boolean {
        return hosts.any { url.contains(it) }
    }

    /// 输出的临时目录名
    fun getOutputPath(): String {
        return host
    }

    /// 解析的域名
    var currentHost: String

    fun outputChapterTitle(): Boolean {
        return true
    }

    operator fun Element.get(i: Int): Element {
        return this.child(i)
    }

    override fun getOutputChapterTitle(chapterMetaEntity: ChapterMetaEntity): String {
        val name = chapterMetaEntity.name.split(" ").let {
            if (it.isEmpty()) {
                return@let "无题"
            }
            return@let if (it.count() >= 2) {
                it.subList(1, it.count()).joinToString("_")
            } else {
                it.first()
            }
        }
        return String.format("第%04d章 %s", chapterMetaEntity.index, name)
    }

    fun watermark(): Map<Regex, String> = emptyMap()

    fun parseHtml(text: String): Document {
        return Jsoup.parse(text)
    }

    fun replaceWatermark(content: String): String {
        val map = watermark()

        if (map.isEmpty()) {
            return content
        }

        var text = content
        for ((regex, target) in map) {
            text = text.replace(regex, target)
        }
        return text
    }

    fun isSupported(): Boolean

    fun searchBook(keyword: String): List<String>
}
